<?php

namespace App\Console\Commands;

use App\Api\Controllers\Config\CqcPayConfigController;
use App\Common\RefundSuccessAction;
use App\Models\Bi\BiOrder;
use App\Models\Order;
use App\Models\RefundOrder;
use App\Models\Store;
use App\Services\Pay\PayService;
use App\Services\PrintSqlService;
use App\Services\Store\StoreMchService;
use App\Util\LockUtil;
use App\Util\SqlWhenUtil;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class DbAddChannel extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'db:add-channel {day?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'db:add-channel';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        dd(json_encode([
            "anem"=>"你hi哈哈哈"
        ],JSON_UNESCAPED_UNICODE));

        PrintSqlService::listen();
        $query = BiOrder::query()->from("orders_202504 as orders");
        $query->first();
        dd(123231);
        Order::query()->where("created_at", ">=", "2025-04-08 20:00:00")
            ->whereIn("pay_status", [1, 6])
            ->chunk(100, function ($orders) {
                foreach ($orders as $order) {
                    $data = [
                        "out_trade_no" => $order->out_trade_no,
                        "type" => 1,
                        "from" => "pay",
                    ];
                    $redis = Redis::connection('amqpQueue');
                    $redis->rPush("payListener", json_encode($data));
                }
            });
        exit();
//        $lists = Order::query()->where("pay_time", ">=", "2024-10-21 17:11:49")->where("pay_time", "<=", "2024-10-21 17:12:31")->get();
//        foreach ($lists as $v) {
//            $data = [
//                "out_trade_no" => $v->out_trade_no,
//                "type" => 1,
//                "from" => "pay",
//            ];
//            $redis = Redis::connection('amqpQueue');
//            $redis->rPush("payListener", json_encode($data));
//        }
        dd("刷订单数据");
//        select  orders . out_trade_no,orders . created_at  from  orders
//left join refund_orders on orders . out_trade_no = refund_orders . out_trade_no
//where orders . created_at >= "2025-02-01 00:00:00" and orders . pay_status = 6 and refund_orders . id is NULL
        //刷订单数据,投递到amqp
        $refundOrders = Order::query()->leftJoin("refund_orders", "orders.out_trade_no", "=", "refund_orders.out_trade_no")
            ->select(["orders.total_amount", "orders.out_trade_no",
                "orders.created_at", "orders.store_id", "orders.merchant_id",
                "orders.ways_type", "orders.ways_source"])
            ->where("orders.created_at", ">=", "2025-02-01 00:00:00")
            ->where("orders.pay_status", 6)
//            ->where("orders.out_trade_no", "wxCib20250307191447269503781")
            ->whereNull("refund_orders.id")
            ->get();
        foreach ($refundOrders as $refundOrder) {
            $refund = DB::table("all_refund_orders")->where("out_trade_no", $refundOrder->out_trade_no)->first();
            $refund_time = $refund->refund_time;
            if (empty($refund_time)) {
                $refund_time = $refundOrder->created_at;
            }
            $refund_amount = (float)$refund->refund_amount;
            if (empty($refund_amount)) {
                $refund_amount = (float)$refundOrder->total_amount;
            }
            RefundOrder::query()->insert([
                'out_trade_no' => $refundOrder->out_trade_no,
                'trade_no' => "",
                'store_id' => $refundOrder->store_id,
                'merchant_id' => $refundOrder->merchant_id,
                'type' => $refundOrder->ways_type,
                'ways_source' => $refundOrder->ways_source,
                'refund_amount' => $refund_amount,//退款金额
                'refund_no' => $refundOrder->out_trade_no,//退款单号
                "created_at" => $refund_time
            ]);
            sleep(1);
            RefundSuccessAction::action([
                'out_trade_no' => $refundOrder->out_trade_no,
                "refund_no" => $refundOrder->out_trade_no
            ]);
        }
        dd("伪造订单数据,投递到amqp");
        PrintSqlService::listen();
        //在这里测试重庆商户号

        $result = (new CqcPayConfigController())->merchant("2025022414211681307", 16173);
        dd($result);
        $aa = StoreMchService::getMchNo("202110121063873131", "wingpay");
        dd($aa);
        //在这里
        $util = new SqlWhenUtil();
        $data = [
            [
                "id" => 707,
                "store_name" => "测试商户___11",
                "store_short_name" => "测试商户____111",
            ],
            [
                "id" => 708,
                "store_name" => "阜南县外卖电子商务服务中心___222",
                "store_short_name" => "阜南县外卖电子商务服务中心___222",
            ]
        ];
        list($whereValue, $update) = $util->caseSql($data, "id");
        //更新数据
        PrintSqlService::listen();
//        Store::query()->where($where)->update($update);
        Store::query()->select(["id", "store_name", "store_short_name"])->whereIn("id", $whereValue)->get()->toArray();

        Store::query()->whereIn("id", $whereValue)->update($update);
        dd($where, $update);
        $isRun = LockUtil::lock("out_trade_no_" . "11111111111111111111");
        dd($isRun);
        dd("测试redis");
        //09-24 - 10-20 数据要重新计算
        /**
         * select  a.out_trade_no,b.out_trade_no from  orders as a
         * left join bi_bill_logs as b
         * on a.out_trade_no=b.out_trade_no where a.pay_time>="2024-10-20 00:00:00" and a.pay_time<="2024-10-20 23:59:59" and a.pay_status in (1,6) and b.out_trade_no is null     **/
        $time = $this->argument('day');
        if (empty($time)) {
            $time = "2024-10-20";
        }
        $start_time = date("Y-m-d 00:00:00", strtotime($time));
        $end_time = date("Y-m-d 23:59:59", strtotime($time));
        $lists = Order::query()->from("orders as a")->select(["a.*"])->leftJoin("bi_bill_logs as b", "a.out_trade_no", "=", "b.out_trade_no")
            ->where("a.pay_time", ">=", $start_time)
            ->where("a.pay_time", "<=", $end_time)
            ->whereIn("pay_status", [1, 6])
            ->whereNull("b.out_trade_no")
            ->whereNotIn("a.out_trade_no", ["20241020000116209dp0000069cf9yDN", "20241020005424940mY00000243ddrQu"])
            ->get();
        $i = 0;
        foreach ($lists as $v) {
            $i++;
            //处理支付数据
            PayService::payOkHandle([
                'out_trade_no' => $v->out_trade_no,
            ]);
            if ($v->pay_status == 6) {
                //10s后在退款
                sleep(5);
                //处理退款数据
                RefundSuccessAction::action([
                    'out_trade_no' => $v->out_trade_no,
                    "refund_no" => $v->refund_no
                ]);
            }
            if (in_array($rand = rand(0, 60), [16])) {
                dump($time . "_rand_" . $rand);
                sleep(1);
            }
        }
        dd("刷遗漏的订单数据，从913开始刷:条数" . $i);
//        select * from orders where pay_time >= "2024-10-21 17:11:50" and pay_time <= "2024-10-21 17:12:30"
        $lists = Order::query()->where("pay_time", ">=", "2024-10-21 17:11:49")->where("pay_time", "<=", "2024-10-21 17:12:31")->get();
        foreach ($lists as $v) {
            $data = [
                "out_trade_no" => $v->out_trade_no,
                "type" => 1,
                "from" => "pay",
            ];
            $redis = Redis::connection('amqpQueue');
            $redis->rPush("payListener", json_encode($data));
        }
        dd("投递close");
        //在这里处理数据
        //在这里测试redis
        $data = [
            "out_trade_no" => "20240912003807996615491",
            "refund_no" => "83620240912631755448",
            "type" => 2
        ];
        $redis = Redis::connection('amqpQueue');
        $redis->rPush("payListener", json_encode($data));
        dd(122121);
        $ways = DB::table("user_rates")->whereIn("ways_type", [30020, 30021, 30022])->get();
        $dbData = [];
        foreach ($ways as $k => $way) {
            $ways_type = 0;
            if ($way->ways_type == 30020) {
                $ways_type = 30023;
            } else if ($way->ways_type == 30021) {
                $ways_type = 30024;
            } else if ($way->ways_type == 30022) {
                $ways_type = 30025;
            }
            $dbData[] = [
                'user_id' => $way->user_id,
                'rate' => $way->rate,//代理商的成本
                'rate_a' => $way->rate_a,//代理商贷记卡的成本
                'rate_b' => $way->rate_b,
                'rate_b_top' => $way->rate_b_top,
                'rate_c' => $way->rate_c,//代理商贷记卡的成本
                'rate_d' => $way->rate_d,
                'rate_d_top' => $way->rate_d_top,
                'settlement_type' => $way->settlement_type,
                'store_all_rate' => $way->store_all_rate,
                'store_all_rate_a' => $way->store_all_rate_a,
                'store_all_rate_b' => $way->store_all_rate_b,
                'store_all_rate_b_top' => $way->store_all_rate_b_top,
                'store_all_rate_c' => $way->store_all_rate_c,
                'store_all_rate_d' => $way->store_all_rate_d,
                'store_all_rate_d_top' => $way->store_all_rate_d_top,
                'ways_type' => $ways_type,
                'company' => "unionpay_merch_v2",
                'rate_e' => $way->rate_e,//代理商贷记卡的成本
                'rate_f' => $way->rate_f,
                'rate_f_top' => $way->rate_f_top,
                'store_all_rate_e' => $way->store_all_rate_e,
                'store_all_rate_f' => $way->store_all_rate_f,
                'store_all_rate_f_top' => $way->store_all_rate_f_top,
                'status' => $way->status,
                'server_rate' => $way->server_rate,
                'yu_rate' => $way->yu_rate,
                'era_rate' => $way->era_rate,
                "created_at" => date("Y-m-d H:i:s", time()),
                "updated_at" => date("Y-m-d H:i:s", time())
            ];

        }
        DB::table("user_rates")->insert($dbData);
    }
}
